package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.RRException;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.vo.Catelog2Vo;;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    RedissonClient redisson;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 树型显示
     *
     * @return
     */
    @Override
    public List<CategoryEntity> listWithTree() {
        // 1.查出所有分类
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);

        // 2.组装成父子的树形结构

        // 2.1).找到一级分类
        List<CategoryEntity> treeMenus = categoryEntities.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == 0;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).map(menu -> {
            menu.setChildren(getChildren(menu, categoryEntities));
            return menu;
        }).collect(Collectors.toList());

        return treeMenus;
    }


    /**
     * 递归找出父子结点的关系
     *
     * @param rootMenu
     * @param allMenus
     * @return
     */
    private List<CategoryEntity> getChildren(CategoryEntity rootMenu, List<CategoryEntity> allMenus) {

        // 1. 找到子菜单
        List<CategoryEntity> childrenList = allMenus.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid().equals(rootMenu.getCatId());
        }).map(menu -> {
            menu.setChildren(getChildren(menu, allMenus));
            return menu;
            // 2.菜单的排序
        }).sorted((m1, m2) -> {
            return (m1.getSort() == null ? 0 : m1.getSort()) - (m2.getSort() == null ? 0 : m2.getSort());
        }).collect(Collectors.toList());
        return childrenList;
    }

    @Override
    public void removeMenus(List<Long> asList) {
        System.out.println("删除的数据为： ++ ++++" + asList);
        // 逻辑删除
        int result = baseMapper.deleteBatchIds(asList);
        if (result < 0) {
            throw new RRException("删除失败");
        }
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        ArrayList<Long> paths = new ArrayList<>();
//        findParentPath(catelogId, paths);

        // 非递归
        paths.add(catelogId);
        CategoryEntity category = this.getById(catelogId);
        while (category.getParentCid() != 0) {
            paths.add(category.getParentCid());
            category = this.getById(category.getParentCid());
        }
        // 将列表反转
        Collections.reverse(paths);

        return paths.toArray(new Long[paths.size()]);
    }

    /**
     * 级联更新
     * @CacheEvict 失效模式
     * @param category
     */
    @CacheEvict(value = "category", key = "'level1Categorys'") // 将相关缓存删除
    // 失效模式
    @Caching(evict = {
            @CacheEvict(value = "category", key = "'getLevel1Categorys'"),
            @CacheEvict(value = "category", key = "'getCatalogJson'")
    })
    // 双写模式
//    @CachePut()
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.baseMapper.updateById(category);
        if (!StringUtils.isEmpty(category.getName())) {
            // 更新关联表中的数据
            categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
        }
    }

    /**
     * 获取所有的 1 级分类
     *
     * @return
     */
    // 每个缓存需要指定放到哪个名字的缓存，【缓存按业务分区】
    // key = "" 设置key值
    // sync = true 加本地锁，解决缓存击穿
    @Cacheable(value = {"category"}, key = "'getLevel1Categorys'", sync = true) // 代表当前结果需要缓存，如果缓存有方法不用调用，如果没有就调用方法，并将方法的返回值放入缓存中
    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        System.out.println("getLevel1Categorys...");
        List<CategoryEntity> categoryEntityList = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));

        return categoryEntityList;
    }

    /**
     * 使用springcache注解来使用缓存
     * @return
     */
    @Cacheable(value = "category", key = "'getCatalogJson'")
    @Override
    public Map<String, List<Catelog2Vo>> getCatalogJson() {
        System.out.println("查询数据库！");
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        // 1.查出所有一级分类
        List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0L);
        // 2.分装数据
        Map<String, List<Catelog2Vo>> collect = level1Categorys.stream().collect(Collectors.toMap(l1 -> l1.getCatId().toString(), v -> {

            // 每一个的一级分类，查找到这个一级分类的二级分类
            List<CategoryEntity> categoryEntities2 = getParent_cid(selectList, v.getCatId());

            List<Catelog2Vo> catelog2Vos = null;
            if (categoryEntities2 != null) {
                // 将二级分类封装成为指定的vo
                catelog2Vos = categoryEntities2.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());

                    // 查找二级分类对应的三级分类
                    List<CategoryEntity> categoryEntities3 = getParent_cid(selectList, l2.getCatId());
                    if (categoryEntities3 != null) {
                        // 将三级分类分装成对应的vo
                        List<Catelog2Vo.Catelog3Vo> collect3 = categoryEntities3.stream().map(l3 -> {
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                        // 设置三级分类的集合
                        catelog2Vo.setCatalog3List(collect3);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return catelog2Vos;
        }));

        return collect;
    }

    // 获取分类数据
    public Map<String, List<Catelog2Vo>> getCatalogJson2() {
        // 给缓存中放json字符串， 拿出的json字符串要逆转为能用的对象类型 【序列化和反序列化】

        /**
         * 1.空结果缓存，解决缓存穿透
         * 2.设置过期时间(加随机值)， 解决缓存雪崩
         * 3.加锁， 解决缓存击穿
         */

        // 1.加入缓存逻辑，缓存中的为json字符串
        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
        if (StringUtils.isEmpty(catalogJSON)) {
            // 2.缓存中没有查询数据库
            System.out.println("缓存不命中... 查询数据库... ");
            Map<String, List<Catelog2Vo>> catalogJsonFromDb = getCatalogJsonFromDbWithRedisLock();
            return catalogJsonFromDb;
        }

        System.out.println("缓存命中.. 直接返回");
        // 4.将获得的字符串转为指定的对象
        Map<String, List<Catelog2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
        });

        return result;
    }

    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWithRedissionLock() {
        // 1.锁的名字，越细越快
        RLock lock = redisson.getLock("catalogJson-lock");
        lock.lock();

        Map<String, List<Catelog2Vo>> dataFromDb = null;
        try {
            dataFromDb = getDataFromDb();
        } finally {
            // 释放锁
            lock.unlock();
        }
        return dataFromDb;
    }

    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWithRedisLock() {
        // 1. 占分布式锁，去redis占坑
        String uuid = UUID.randomUUID().toString();
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid, 300, TimeUnit.SECONDS);
        if (lock) {
            // 设置锁的过期时间， 必须和加锁是同步的，原子的
//            redisTemplate.expire("lock", 30, TimeUnit.SECONDS);
            // 加所成功执行业务
            Map<String, List<Catelog2Vo>> dataFromDb = null;
            try {
                dataFromDb = getDataFromDb();
            } finally {
                //            redisTemplate.delete("lock"); // 将锁删除

                // 获取值对比 + 对比成功删除 ————> 原子操作 lua脚本解锁
                String script = "if redis.call(\"get\",KEYS[1]) == ARGV[1] then return redis.call(\"del\",KEYS[1]) else return 0 end";
                redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class)
                        , Arrays.asList("lock"), uuid);
            }
            return dataFromDb;
        } else {
            // 加锁失败，重试
            // 休眠100ms重试
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {

            }
            return getCatalogJsonFromDbWithRedisLock(); // 自旋的方式
        }
    }

    // 查询数据库获取数据
    private Map<String, List<Catelog2Vo>> getDataFromDb() {
        // 确定缓存中是否含有数据
        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
        if (!StringUtils.isEmpty(catalogJSON)) {
            // 缓存不为空直接返回
            Map<String, List<Catelog2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
            });
            return result;
        }
        /**
         * 将数据库的多次查询变为一次查询
         */
        List<CategoryEntity> selectList = baseMapper.selectList(null);

        // 1.查出所有一级分类
        List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0L);

        // 2.分装数据
        Map<String, List<Catelog2Vo>> collect = level1Categorys.stream().collect(Collectors.toMap(l1 -> l1.getCatId().toString(), v -> {

            // 每一个的一级分类，查找到这个一级分类的二级分类
            List<CategoryEntity> categoryEntities2 = getParent_cid(selectList, v.getCatId());

            List<Catelog2Vo> catelog2Vos = null;
            if (categoryEntities2 != null) {
                // 将二级分类封装成为指定的vo
                catelog2Vos = categoryEntities2.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());

                    // 查找二级分类对应的三级分类
                    List<CategoryEntity> categoryEntities3 = getParent_cid(selectList, l2.getCatId());
                    if (categoryEntities3 != null) {
                        // 将三级分类分装成对应的vo
                        List<Catelog2Vo.Catelog3Vo> collect3 = categoryEntities3.stream().map(l3 -> {
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                        // 设置三级分类的集合
                        catelog2Vo.setCatalog3List(collect3);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return catelog2Vos;
        }));

        // 3.查到的数据再放入缓存，将对象转为json放入缓存中
        String s = JSON.toJSONString(collect);
        redisTemplate.opsForValue().set("catalogJSON", s);

        return collect;
    }

    // 从数据库查询并分类数据， 并将查询到的数据放入缓存中
    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWithLocalLock() {

        synchronized (this) {
            return getDataFromDb();
        }


    }

    // 抽取查询方法
    private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList, Long parent_cid) {
//        return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));

        List<CategoryEntity> collect = selectList.stream().filter(item -> {
            return item.getParentCid() == parent_cid;
        }).collect(Collectors.toList());

        return collect;
    }

    // 递归获取父节点的数据 [子 --> 父]
    private void findParentPath(Long catelogId, ArrayList paths) {
        // 将当前节点的id加入列表中
        paths.add(catelogId);
        CategoryEntity category = this.getById(catelogId);
        // 将父节点的id加入列表中
        if (category.getParentCid() != 0) {
            findParentPath(category.getParentCid(), paths);
        }
    }

}